import * as React from 'react'
import {compose} from 'recompose'
import {Form} from 'antd'

export default (ComposedComponent: React.Component) => {
    class WithForm extends React.Component {
        render() {
            const submit = ({e, mutate, otherValues, callback, parseValues}) => {
                (e || event).preventDefault();
                this.props.form.validateFields(async (err: any, values: any) => {
                    if (!err) {
                        const ret = await  mutate({
                            variables: {
                                input: {
                                    ...(parseValues
                                            ? parseValues(values)
                                            : (values || {})
                                    ),
                                    ...(otherValues || {})
                                }
                            }
                        });
                        callback && callback(ret)
                        return ret
                    } else {
                        console.log(err)
                    }
                });
            }
            return (<ComposedComponent {...this.props} submit={submit}/>)
        }
    }

    return compose(Form.create())(WithForm)
}